import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  useColorScheme,
  ScrollView,
  TextInput,
  Alert,
  Modal,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { RootStackParamList } from '../types';

interface CustomTimer {
  id: string;
  name: string;
  minutes: number;
}

const PomodoroTimerScreen: React.FC<NativeStackScreenProps<RootStackParamList, 'PomodoroTimer'>> = ({ route, navigation }) => {
  const isDarkMode = useColorScheme() === 'dark';
  const initialMinutes = route.params?.initialMinutes;
  const initialSeconds = route.params?.initialSeconds;
  const presetName = route.params?.presetName;
  
  // 状态
  const [isActive, setIsActive] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [timeLeft, setTimeLeft] = useState(300); // 默认5分钟
  const [initialTime, setInitialTime] = useState(300); // 记录初始设置的时间
  
  // 自定义计时器状态
  const [customTimers, setCustomTimers] = useState<CustomTimer[]>([
    { id: '1', name: '泡面', minutes: 3 },
    { id: '2', name: '短休息', minutes: 5 },
    { id: '3', name: '面膜', minutes: 15 },
    { id: '4', name: '番茄钟', minutes: 25 },
  ]);
  const [showAddTimerModal, setShowAddTimerModal] = useState(false);
  const [newTimerName, setNewTimerName] = useState('');
  const [newTimerMinutes, setNewTimerMinutes] = useState('');
  
  // 格式化时间显示
  const formatTime = (time: number): string => {
    const h = Math.floor(time / 3600);
    const m = Math.floor((time % 3600) / 60);
    const s = time % 60;
    
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
  };
  
  // 开始计时器
  const startTimer = () => {
    if (timeLeft <= 0) {
      Alert.alert('提示', '请先设置时间');
      return;
    }
    setIsActive(true);
    setIsPaused(false);
  };
  
  // 暂停计时器
  const pauseTimer = () => {
    setIsPaused(true);
  };
  
  // 继续计时器
  const resumeTimer = () => {
    setIsPaused(false);
  };
  
  // 重置计时器
  const resetTimer = () => {
    setIsActive(false);
    setIsPaused(false);
    setTimeLeft(initialTime);
  };
  
  // 初始化从路由参数设置时间
  useEffect(() => {
    if (initialMinutes !== undefined || initialSeconds !== undefined) {
      const mins = initialMinutes || 0;
      const secs = initialSeconds || 0;
      const totalSeconds = mins * 60 + secs;
      
      setTimeLeft(totalSeconds);
      setInitialTime(totalSeconds);
    }
  }, [initialMinutes, initialSeconds]);

  // 计时器逻辑
  useEffect(() => {
    let interval: NodeJS.Timeout | null = null;
    
    if (isActive && !isPaused) {
      interval = setInterval(() => {
        setTimeLeft((time) => {
          if (time <= 1) {
            clearInterval(interval as NodeJS.Timeout);
            setIsActive(false);
            Alert.alert('提示', '时间到了！');
            return 0;
          }
          return time - 1;
        });
      }, 1000);
    } else if (interval) {
      clearInterval(interval);
    }
    
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isActive, isPaused]);
  
  // 快速设置时间
  const setQuickTime = (mins: number) => {
    const totalSeconds = mins * 60;
    setTimeLeft(totalSeconds);
    setInitialTime(totalSeconds);
    setIsActive(false);
    setIsPaused(false);
  };
  
  // 添加自定义计时器
  const addCustomTimer = () => {
    if (!newTimerName.trim()) {
      Alert.alert('提示', '请输入计时器名称');
      return;
    }
    
    const minutes = parseInt(newTimerMinutes);
    if (isNaN(minutes) || minutes <= 0) {
      Alert.alert('提示', '请输入有效的分钟数');
      return;
    }
    
    const newTimer: CustomTimer = {
      id: Date.now().toString(),
      name: newTimerName.trim(),
      minutes: minutes
    };
    
    setCustomTimers([...customTimers, newTimer]);
    setNewTimerName('');
    setNewTimerMinutes('');
    setShowAddTimerModal(false);
  };
  
  // 删除自定义计时器
  const deleteCustomTimer = (id: string) => {
    Alert.alert(
      '确认删除',
      '确定要删除这个计时器吗？',
      [
        { text: '取消', style: 'cancel' },
        { 
          text: '删除', 
          style: 'destructive',
          onPress: () => {
            setCustomTimers(customTimers.filter(timer => timer.id !== id));
          }
        }
      ]
    );
  };
  
  return (
    <ScrollView style={[styles.container, isDarkMode && styles.darkContainer]}>
      <Text style={[styles.title, isDarkMode && styles.lightText]}>
        计时器
      </Text>
      
      {/* 时间显示 */}
      <View style={styles.timerCard}>
        <Text style={[styles.timerDisplay, isDarkMode && styles.lightText]}>
          {formatTime(timeLeft)}
        </Text>
        
        
        {/* 控制按钮 */}
        <View style={styles.controlsContainer}>
          {!isActive ? (
            <TouchableOpacity 
              style={[styles.button, { backgroundColor: '#4CAF50' }]} 
              onPress={startTimer}
            >
              <Text style={styles.buttonText}>开始</Text>
            </TouchableOpacity>
          ) : isPaused ? (
            <TouchableOpacity 
              style={[styles.button, { backgroundColor: '#4CAF50' }]} 
              onPress={resumeTimer}
            >
              <Text style={styles.buttonText}>继续</Text>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity 
              style={[styles.button, { backgroundColor: '#FF9800' }]} 
              onPress={pauseTimer}
            >
              <Text style={styles.buttonText}>暂停</Text>
            </TouchableOpacity>
          )}
          
          <TouchableOpacity 
            style={[styles.button, { backgroundColor: '#F44336' }]} 
            onPress={resetTimer}
          >
            <Text style={styles.buttonText}>重置</Text>
          </TouchableOpacity>
        </View>
      </View>
      
      {/* 常用计时器 */}
      <View style={styles.commonTimersContainer}>
        <View style={styles.sectionHeader}>
          <Text style={[styles.sectionTitle, isDarkMode && styles.lightText]}>
            常用计时器
          </Text>
          <TouchableOpacity 
            style={styles.addButton}
            onPress={() => setShowAddTimerModal(true)}
          >
            <Text style={styles.addButtonText}>+ 新增</Text>
          </TouchableOpacity>
        </View>
        
        <View style={styles.quickTimersContainer}>
          {customTimers.map((timer) => (
            <TouchableOpacity 
              key={timer.id}
              style={styles.quickTimerButton}
              onPress={() => setQuickTime(timer.minutes)}
              onLongPress={() => deleteCustomTimer(timer.id)}
            >
              <Text style={styles.quickTimerTime}>{timer.minutes}:00</Text>
              <Text style={styles.quickTimerLabel}>{timer.name}</Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>
      
      {/* 添加自定义计时器模态框 */}
      <Modal
        visible={showAddTimerModal}
        transparent={true}
        animationType="slide"
        onRequestClose={() => setShowAddTimerModal(false)}
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>添加常用计时器</Text>
            
            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>名称</Text>
              <TextInput
                style={styles.textInput}
                value={newTimerName}
                onChangeText={setNewTimerName}
                placeholder="例如：煮鸡蛋"
              />
            </View>
            
            <View style={styles.inputGroup}>
              <Text style={styles.inputLabel}>时间（分钟）</Text>
              <TextInput
                style={styles.textInput}
                value={newTimerMinutes}
                onChangeText={setNewTimerMinutes}
                keyboardType="numeric"
                placeholder="例如：10"
              />
            </View>
            
            <View style={styles.modalButtons}>
              <TouchableOpacity
                style={[styles.modalButton, styles.cancelButton]}
                onPress={() => setShowAddTimerModal(false)}
              >
                <Text style={styles.modalButtonText}>取消</Text>
              </TouchableOpacity>
              
              <TouchableOpacity
                style={[styles.modalButton, styles.saveButton]}
                onPress={addCustomTimer}
              >
                <Text style={[styles.modalButtonText, styles.saveButtonText]}>保存</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  darkContainer: {
    backgroundColor: '#121212',
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30,
    color: '#333',
  },
  lightText: {
    color: '#fff',
  },
  timerCard: {
    backgroundColor: '#fff',
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  timerDisplay: {
    fontSize: 60,
    fontWeight: 'bold',
    textAlign: 'center',
    color: '#333',
    marginBottom: 30,
  },
  controlsContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 10,
  },
  button: {
    paddingVertical: 15,
    paddingHorizontal: 30,
    borderRadius: 30,
    marginHorizontal: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 4,
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 15,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
  },
  addButton: {
    padding: 5,
  },
  addButtonText: {
    color: '#2196F3',
    fontSize: 16,
    fontWeight: 'bold',
  },
  commonTimersContainer: {
    backgroundColor: '#fff',
    borderRadius: 16,
    padding: 20,
    marginBottom: 20,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  quickTimersContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  quickTimerButton: {
    width: '48%',
    backgroundColor: '#f0f0f0',
    borderRadius: 12,
    padding: 15,
    alignItems: 'center',
    marginBottom: 15,
  },
  quickTimerTime: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 5,
  },
  quickTimerLabel: {
    fontSize: 14,
    color: '#666',
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  modalContent: {
    backgroundColor: '#fff',
    borderRadius: 16,
    padding: 20,
    width: '85%',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
    color: '#333',
  },
  inputGroup: {
    marginBottom: 15,
  },
  inputLabel: {
    fontSize: 14,
    marginBottom: 5,
    color: '#666',
  },
  textInput: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 8,
    fontSize: 16,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  modalButton: {
    paddingVertical: 12,
    paddingHorizontal: 20,
    borderRadius: 8,
    flex: 1,
    marginHorizontal: 5,
    alignItems: 'center',
  },
  cancelButton: {
    backgroundColor: '#f0f0f0',
  },
  saveButton: {
    backgroundColor: '#2196F3',
  },
  modalButtonText: {
    fontWeight: 'bold',
    fontSize: 16,
    color: '#333',
  },
  saveButtonText: {
    color: '#fff',
  },
});

export default PomodoroTimerScreen;